package org.yxing.palpalgps.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.utils.Helper;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class AsyncUpload {
    private static final String TAG = AsyncUpload.class.getSimpleName();
    
    private Context mContext;
    private OnUploadListener listener;
    private ProgressDialog pd;
    
    public AsyncUpload(Context context) {
        mContext = context;
        pd = new ProgressDialog(mContext);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setMessage(mContext.getString(R.string.progress));
    }
    
    public void setOnUploadListener(OnUploadListener listener) {
        this.listener = listener;
    }
    
    public void upload(final String url, final List<BasicNameValuePair> params, final File uploadFile, final String inputName) {
        pd.show();
        
        new Thread(){
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(url);
                MultipartEntity m = new MultipartEntity();
                
                
                try {
                    //set params
                    for (BasicNameValuePair b : params) 
                        m.addPart(b.getName(), new StringBody(b.getValue()));
                    
                    //add file to params
                    InputStream is = new FileInputStream(uploadFile);
                    InputStreamBody isb = new InputStreamBody(is, uploadFile.getName());
                    m.addPart(inputName, isb);
                    
                    post.setEntity(m);
                    HttpResponse resp = client.execute(post);
                    
                    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent(), HTTP.UTF_8));
                        StringBuffer sb = new StringBuffer();
                        int l;
                        char[] buf = new char[512];
                        while ((l = br.read(buf)) != -1) {
                            sb.append(buf, 0, l);
                        }
                        mHandler.sendMessage(mHandler.obtainMessage(0, sb.toString()));
                        Log.d(TAG, "finish");
                    } else 
                        Log.w(TAG, "上传文件出错了：" + EntityUtils.toString(resp.getEntity()));
                    is.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    pd.cancel();
                }
            }
        }.start();
    }
    
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (listener != null) {
                listener.onComplate((String)msg.obj);
            }
        }
    };
    
    public interface OnUploadListener {
        public void onComplate(String result);
        public void onError();
    }
}
